<?php


namespace app\index\controller;


use app\model\Boutcardorder;
use app\model\Config;
use app\model\Heepay;
use app\model\Member;
use app\model\MemberCashlogs;
use app\model\Order;
use app\model\Paymethod;
use app\model\StoreBail;
use app\model\TechnicalBail;
use app\model\Tongue;
use app\model\Viporder;
use app\model\Wxpay;
use GuzzleHttp\Client;

class HeepayController extends Base
{
    public function index()
    {

        $orderid = intval(input('post.orderid'));
        $money = input('post.money');
        $money = round($money, 2);
        $type = input('post.type');
        if ($type == "order") {
            if (!empty($orderid)) {
                $orderdata = Order::find($orderid);
                if (!empty($orderdata)) {
                    $orderdata = $orderdata->toArray();

                    if ($orderdata['is_user_send'] == 1 &&
                        $orderdata['order_status_id'] == 1 &&
                        $orderdata['ptype'] == 2 &&
                        $orderdata['price_type'] == 1 &&
                        $orderdata['is_select_quotation'] == 0
                    ) {
                        return $this->json(['errno' => 1, 'msg' => '请先选择师傅']);
                    }
                } else {
                    return $this->json(['errno' => 1, 'msg' => '订单不存在']);
                }

                //构造支付参数
                $paydata = array(
                    'goods_name' => '订单支付',
                    'agent_bill_id' => $orderid,
                    'pay_amt' => $money,
                );
            }
        } elseif ($type == "vip") {
            $paydata = array(
                'goods_name' => '购买会员等级',
                'agent_bill_id' => 'vip-' . $orderid . '-' . time(),
                'pay_amt' => $money,
            );
        } elseif ($type == "additional") {
            if (!empty($orderid)) {
                $orderdata = Order::find($orderid);
                if (!empty($orderdata)) {
                    $orderdata = $orderdata->toArray();
                } else {
                    return $this->json(['errno' => 1, 'msg' => '订单不存在']);
                }

                //构造支付参数
                $paydata = array(
                    'goods_name' => '支付尾款',
                    'agent_bill_id' => 'additional-' . $orderid,
                    'pay_amt' => $money,
                );
            }
        } elseif ($type == "paybill") {
            $paydata = array(
                'goods_name' => '优惠买单',
                'agent_bill_id' => 'paybill-' . time(),
                'pay_amt' => $money,
            );
        } elseif ($type == "recharge") {

            $paydata = array(
                'goods_name' => '充值',
                'agent_bill_id' => 'recharge-' . UID(),
                'pay_amt' => $money,
            );
        } elseif ($type == "tongue") {

            $paydata = array(
                'goods_name' => 'AI舌诊',
                'agent_bill_id' => 'tongue-' . $orderid,
                'pay_amt' => $money,
            );
        } elseif ($type == 'boutorder'){
            $paydata = array(
                'goods_name' => '次卡订单',
                'agent_bill_id' => 'boutcard-' . $orderid,
                'pay_amt' => $money,
            );
        } elseif ($type == 'technicalbail'){
            $paydata = array(
                'goods_name' => '师傅保证金',
                'agent_bill_id' => 'technicalbail-' . $orderid,
                'pay_amt' => $money,
            );
        } elseif ($type == 'storebail'){
            $paydata = array(
                'goods_name' => '商家保证金',
                'agent_bill_id' => 'storebail-' . $orderid,
                'pay_amt' => $money,
            );
        }

        //生成支付参数，返回给小程序端
        $pay_params = $this->heepay($paydata);

        $client = new Client();

        $response = $client->get( 'https://pay.heepay.com/Payment/Index.aspx?'.http_build_query($pay_params));


        $data = json_decode($response->getBody()->getContents(),true);
        return $this->json(['data'=>$data]);
    }

    public function heepay($paydata)
    {

        $paydata['version'] = 1;
        $paydata['pay_type'] = 30;
        $heepay_settings = Paymethod::gethee_settings();
        $paydata['agent_id'] = (int)$heepay_settings['agent_id'];
        $paydata['agent_bill_time'] =  date('YmdHis');
        $paydata['meta_option'] = Heepay::make($this->userInfo['ptype']);
        $paydata['user_ip'] = '170_178_169_107';
        $paydata['remark'] = '';

        $paydata['notify_url'] = gethost() . TP_APIURL . '/index.php/index/heepay/notify';
        $paydata['return_url'] = "https://";


        $paydata['sign_type'] = 'MD5';
        $paydata['sign'] = Heepay::sign($paydata,$heepay_settings['key']);

        return $paydata;
    }


    //支付回调
    public function notify()
    {
        header("Content-type: text/plain; charset=utf-8");
        $message = input('get.');

        if(!Heepay::checkSign($message)){
            return 'error';
        }

        if ($message['result'] === '1') {
            //支付成功
            $tid = $message['agent_bill_id'];
            $tidarray = explode('-', $tid);


            if (!empty($tidarray[1])) {
                $tid = $tidarray[1];
            }
            if ($tidarray[0] == 'paybill') {

                $cashlogsdata['uid'] = UID();
                $cashlogsdata['uniacid'] = uniacid();
                $cashlogsdata['id'] = '0';
                $cashlogsdata['order_num_alias'] = '0';
                $cashlogsdata['remarks'] = '优惠买单';
                $cashlogsdata['prefix'] = 2;
                $cashlogsdata['amount'] = $message['pay_amt'];
                $cashlogsdata['create_time'] = time();

                MemberCashlogs::create($cashlogsdata);
            } elseif ($tidarray[0] == 'recharge') {

                Member::where('id',$tid)
                    ->inc('balance', $message['pay_amt'])
                    ->update();

                $cashlogsdata['uid'] = $tid;
                $cashlogsdata['uniacid'] = uniacid();
                $cashlogsdata['id'] = '0';
                $cashlogsdata['order_num_alias'] = '0';
                $cashlogsdata['remarks'] = '充值';
                $cashlogsdata['prefix'] = 1;
                $cashlogsdata['amount'] = $message['pay_amt'];
                $cashlogsdata['create_time'] = time();

                MemberCashlogs::create($cashlogsdata);
            } elseif ($tidarray[0] == 'additional') {

                Order::itional_pay($tid);
            } elseif ($tidarray[0] == 'tongue') {
                Tongue::where('id', $tid)->update(['is_pay' => 1]);
            } elseif ($tidarray[0] == 'vip') {
                Viporder::pay_order(['id' => $tid]);
            } elseif ($tidarray[0] == 'boutcard'){
                $data['id'] = $tid;
                $data['payment_code'] = 'hee_pay';
                Boutcardorder::pay_order($data);
            } elseif ($tidarray[0] == 'technicalbail'){
                $data['id'] = $tid;
                TechnicalBail::pay_order($data);
            } elseif ($tidarray[0] == 'storebail'){
                $data['id'] = $tid;
                StoreBail::pay_order($data);
            }else {

                $fee = $message['pay_amt'];
                if (!empty($fee)) {
                    $order = Order::find($tid);
                    if (!empty($order)) {
                        $order = $order->toArray();
                    }
                }

                $data['id'] = $tid;
                $data['user_agent'] = serialize($message);
                $data['payment_code'] = 'hee_pay';
                $ordermod = new Order;
                $ordermod->pay_order($data);
            }
            return "ok";
        } else {
            // 用户支付失败
            return "error";
        }

    }


    public function refundNotify(){

    }
}



